﻿namespace Bowlus.Common
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Reactive.Concurrency;
    using System.Web.Script.Serialization;

    public class ApplicationHost
    {
        public ApplicationHost()
        {
        }

        public ApplicationHost(string jsonString)
        {
            var values = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(jsonString);
            this.Status = values["Status"];
            this.InstanceId = values["InstanceId"];
        }

        public string Status { get; set; }

        public string InstanceId { get; set; }

        public IPEndPoint ApphostHttpEndpoint { get; set; }

        public IEnumerable<TenantDeployment> Deployments { get; set; }

        public string Serialize()
        {
            var values = new Dictionary<string, string> { { "Status", this.Status }, { "InstanceId", this.InstanceId } };

            return new JavaScriptSerializer().Serialize(values);
        }

        public void StartPollingStatus()
        {
            var timerInterval = Settings.AppHostStatusPollInterval;

            this.Poll(timerInterval);
        }

        private void Poll(TimeSpan timerInterval)
        {
            var appHost =
                BowlusHostingEnvironment.GetCurrentAppHosts().Where(
                    ah => ah.ApphostHttpEndpoint.Address.ToString().Equals(this.ApphostHttpEndpoint.Address.ToString()))
                    .ToList();

            if (!appHost.Any())
            {
                this.Status = ApplicationHostStatus.Deleting;
                return;
            }

            var host = appHost.First();
            switch (host.Status)
            {
                case "Deleting":
                    this.Status = ApplicationHostStatus.Deleting;
                    return;
                case "Running":
                    this.Status = ApplicationHostStatus.Added;
                    return;
            }

            Scheduler.ThreadPool.Schedule(timerInterval, () => this.Poll(timerInterval));
        }
    }
}
